<template>
  <div class="start-model-container">
    <h2>算法模型启动服务</h2>
    
    <div class="status-panel">
      <h3>连接状态</h3>
      <div class="status-item">
        <span>当前状态:</span>
        <span :class="['status-badge', connectionStateClass]">
          {{ connectionStateText }}
        </span>
      </div>
      <div class="status-item">
        <span>连接地址:</span>
        <span>{{ wsUrl }}</span>
      </div>
    </div>

    <div class="control-panel">
      <button 
        @click="connect" 
        :disabled="isConnected || isConnecting"
        class="control-button connect-button"
      >
        连接
      </button>
      <button 
        @click="disconnect" 
        :disabled="!isConnected"
        class="control-button disconnect-button"
      >
        断开连接
      </button>
      <button 
        @click="sendStartRequest" 
        :disabled="!isConnected"
        class="control-button start-button"
      >
        启动算法模型
      </button>
    </div>

    <div class="message-panel">
      <h3>消息日志</h3>
      <div class="message-container">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message-item', message.type]"
        >
          <span class="message-time">{{ message.time }}</span>
          <span class="message-content">{{ message.content }}</span>
        </div>
      </div>
      <button @click="clearMessages" class="clear-button">清空日志</button>
    </div>

    <div class="error-panel" v-if="errorMessage">
      <h3>错误信息</h3>
      <div class="error-content">{{ errorMessage }}</div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useWsStore } from '@/store/ws';
import StartModelWebSocketService from '@/ws_service/startModelWsService';

export default {
  name: 'StartModelService',
  setup() {
    const wsStore = useWsStore();
    const wsUrl = wsStore.startModelWsUrl;
    
    // WebSocket服务实例
    let startModelService = null;
    
    // 响应式数据
    const isConnected = ref(false);
    const connectionState = ref('disconnected');
    const messages = ref([]);
    const errorMessage = ref('');
    
    // 计算属性
    const isConnecting = computed(() => connectionState.value === 'connecting');
    const connectionStateClass = computed(() => {
      switch (connectionState.value) {
        case 'connected': return 'status-success';
        case 'connecting': return 'status-warning';
        case 'error': return 'status-error';
        default: return 'status-default';
      }
    });
    
    const connectionStateText = computed(() => {
      switch (connectionState.value) {
        case 'connected': return '已连接';
        case 'connecting': return '连接中';
        case 'error': return '连接错误';
        default: return '未连接';
      }
    });
    
    // 方法
    const addMessage = (content, type = 'info') => {
      messages.value.unshift({
        time: new Date().toLocaleTimeString(),
        content,
        type
      });
      
      // 限制消息数量
      if (messages.value.length > 100) {
        messages.value = messages.value.slice(0, 100);
      }
    };
    
    const connect = () => {
      if (startModelService) {
        startModelService.disconnect();
      }
      
      startModelService = new StartModelWebSocketService(wsUrl);
      
      // 注册事件监听
      startModelService.on('onOpen', (event) => {
        isConnected.value = true;
        connectionState.value = 'connected';
        addMessage('WebSocket连接已建立', 'success');
        wsStore.setStartModelConnectionStatus(true);
        wsStore.setStartModelState('connected');
      });
      
      startModelService.on('onMessage', (event) => {
        try {
          const data = JSON.parse(event.data);
          addMessage(`收到消息: ${JSON.stringify(data)}`, 'message');
          wsStore.setStartModelLastMessage(data);
        } catch (error) {
          addMessage(`收到消息: ${event.data}`, 'message');
          wsStore.setStartModelLastMessage(event.data);
        }
      });
      
      startModelService.on('onError', (error) => {
        addMessage(`错误: ${error.message || JSON.stringify(error)}`, 'error');
        errorMessage.value = error.message || JSON.stringify(error);
        connectionState.value = 'error';
        wsStore.setStartModelError(error.message || JSON.stringify(error));
        wsStore.setStartModelState('error');
      });
      
      startModelService.on('onClose', (event) => {
        isConnected.value = false;
        connectionState.value = 'disconnected';
        addMessage('WebSocket连接已关闭', 'warning');
        wsStore.setStartModelConnectionStatus(false);
        wsStore.setStartModelState('disconnected');
      });
      
      startModelService.on('onStateChange', ({ oldState, newState }) => {
        connectionState.value = newState;
        addMessage(`状态变化: ${oldState} -> ${newState}`, 'info');
        wsStore.setStartModelState(newState);
      });
    };
    
    const disconnect = () => {
      if (startModelService) {
        startModelService.disconnect();
        startModelService = null;
      }
    };
    
    const sendStartRequest = () => {
      if (startModelService && isConnected.value) {
        startModelService.sendStartRequest();
        addMessage('已发送启动算法模型请求', 'info');
      }
    };
    
    const clearMessages = () => {
      messages.value = [];
    };
    
    // 生命周期钩子
    onMounted(() => {
      connect();
    });
    
    onUnmounted(() => {
      disconnect();
    });
    
    return {
      wsUrl,
      isConnected,
      isConnecting,
      connectionState,
      connectionStateClass,
      connectionStateText,
      messages,
      errorMessage,
      connect,
      disconnect,
      sendStartRequest,
      clearMessages
    };
  }
};
</script>

<style scoped>
.start-model-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

h3 {
  color: #555;
  margin-bottom: 10px;
}

.status-panel, .control-panel, .message-panel, .error-panel {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: bold;
  color: white;
}

.status-success {
  background-color: #4caf50;
}

.status-warning {
  background-color: #ff9800;
}

.status-error {
  background-color: #f44336;
}

.status-default {
  background-color: #9e9e9e;
}

.control-panel {
  display: flex;
  gap: 10px;
}

.control-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s;
}

.control-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.connect-button {
  background-color: #4caf50;
  color: white;
}

.connect-button:hover:not(:disabled) {
  background-color: #45a049;
}

.disconnect-button {
  background-color: #f44336;
  color: white;
}

.disconnect-button:hover:not(:disabled) {
  background-color: #d32f2f;
}

.start-button {
  background-color: #2196f3;
  color: white;
}

.start-button:hover:not(:disabled) {
  background-color: #0b7dda;
}

.message-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  background-color: white;
}

.message-item {
  display: flex;
  margin-bottom: 8px;
  padding: 5px;
  border-radius: 4px;
}

.message-item.info {
  background-color: #e3f2fd;
}

.message-item.success {
  background-color: #e8f5e9;
}

.message-item.warning {
  background-color: #fff3e0;
}

.message-item.error {
  background-color: #ffebee;
}

.message-item.message {
  background-color: #f3e5f5;
}

.message-time {
  margin-right: 10px;
  font-size: 0.8em;
  color: #666;
  min-width: 80px;
}

.message-content {
  flex: 1;
  word-break: break-all;
}

.clear-button {
  margin-top: 10px;
  padding: 6px 12px;
  background-color: #9e9e9e;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.clear-button:hover {
  background-color: #757575;
}

.error-content {
  padding: 10px;
  background-color: #ffebee;
  border-radius: 4px;
  color: #d32f2f;
  word-break: break-all;
}
</style>